#include"SeqList.h"

void SLInit(SL* ps)
{
	assert(ps);

	ps->a = (int*)malloc(sizeof(SLDateType) * INIT_CAPACITY);
	if (ps->a == NULL)
	{
		perror("SLInit malloc fail");
		return;
	}

	ps->size = 0;
	ps->capacity = INIT_CAPACITY;
}

void SLDestory(SL* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->size = 0;
}

void CheckCapacity(SL* ps)
{
	if (ps->capacity == ps->size)
	{
		int* tmp = (int*)realloc(ps->a, sizeof(SLDateType) * INIT_CAPACITY * 2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->a = tmp;
		ps->capacity *= 2;
	}
}

void SLPrint(SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}


void PushBack(SL* ps, SLDateType x)
{
	assert(ps);

	CheckCapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;

}

void PopBack(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);

	ps->size--;
}
void PushFront(SL* ps, SLDateType x)
{
	assert(ps);

	CheckCapacity(ps);
	int end = ps->size;
	while (end)
	{
		ps->a[end] = ps->a[end - 1];
		end--;
	}
	ps->a[0] = x;
	ps->size++;

}
void PopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);

	int begin = 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;
}

void SLInsert(SL* ps, SLDateType pos, SLDateType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	int end = ps->size;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}
void SLErase(SL* ps, SLDateType pos)
{
	assert(ps);
	assert(ps->size > 0&&pos<ps->size);

	int end = pos+1;
	while (end < ps->size)
	{
		ps->a[end-1] = ps->a[end];
		end++;
	}
	ps->size--;
}

SLDateType SLFind(SL* ps, SLDateType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x);
			return i;
	}
	return -1;
}